package com.java.wechat.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.auth.service.SysUserService;
import com.java.common.utils.JwtHelper;
import com.java.common.utils.R;
import com.java.model.system.SysUser;
import com.java.vo.wechat.BindPhoneVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/admin/wechat")
@Slf4j
public class WechatController {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private SysUserService sysUserService;

    @Value("${wechat.userInfoUrl}")
    private String userInfoUrl;

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl, HttpServletRequest request){

        //buildAuthorizationUrl三个参数
        //1，授权路径，在哪个路径中获取微信信息
        //2，固定值，授权类型
        //3，授权成功之后，跳转路径，‘guiguoa’装成成 #
        System.out.println(userInfoUrl);
        String redirectURL = wxMpService.getOAuth2Service()
                .buildAuthorizationUrl(userInfoUrl,
                        WxConsts.OAuth2Scope.SNSAPI_USERINFO,
                        URLEncoder.encode(returnUrl.replace("guiguoa", "#")));
        System.out.println(redirectURL);

        return "redirect:" + redirectURL;

    }

    /**
     *
     * @param code 临时票据，
     * @param returnUrl
     * @return
     * @throws Exception
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        //获取accessToken
        WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        //使用获取accessToken获取openid
        String openId = accessToken.getOpenId();
        //获取微信用户信息
        WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);

        //获取用户信息
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));
        String token ="";
        if(null!=sysUser){
            token = JwtHelper.createToken(sysUser.getId(),sysUser.getUsername());
        }
        if(returnUrl.indexOf("?") == -1) {
            return "redirect:" + returnUrl + "?token=" + token + "&openId=" + openId;
        } else {
            return "redirect:" + returnUrl + "&token=" + token + "&openId=" + openId;
        }
    }

    @ApiOperation(value = "微信账号绑定手机")
    @PostMapping("bindPhone")
    @ResponseBody
    public R bindPhone(@RequestBody BindPhoneVo bindPhoneVo) {
        //根据手机号查询数据库
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhone, bindPhoneVo.getPhone()));
        //如果存在更新用户
        if(sysUser!=null){
            sysUser.setOpenId(bindPhoneVo.getOpenId());
            sysUserService.update(sysUser);
            String token = JwtHelper.createToken(sysUser.getId(),sysUser.getUsername());
            return R.ok(token);
        }
        return R.fail().message("手机号码不存在，绑定失败");
    }

}
